package io.github.talelin.latticy.service;

import io.github.talelin.autoconfigure.exception.ForbiddenException;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.common.UserUtil;
import io.github.talelin.latticy.dto.ExpenseDTO;
import io.github.talelin.latticy.entity.Expense;
import io.github.talelin.latticy.repository.ExpenseRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Optional;

@Service
public class ExpenseService {

    @Autowired
    private ExpenseRepository expenseRepository;

    @Autowired
    private RecordService recordService;

    @Autowired
    private UserUtil userUtil;

    public void create(ExpenseDTO dto) {
        Expense expense = new Expense();
        Date now = new Date();
        Long userId = UserUtil.getCurrentUserId();
        Long rootUserId = userUtil.getRootUserId();
        BeanUtils.copyProperties(dto, expense);
        expense.setUserId(userId);
        expense.setExamineUserId(rootUserId);
        expense.setStatus(1);
        expense.setCreateTime(now);
        expenseRepository.save(expense);
        //同步记录
        recordService.create(userId, rootUserId, rootUserId, 2, expense.getId());
    }

    public void updateStatus(Long id, int status) {
        Expense expense = this.get(id);
        expense.setStatus(status);
        expenseRepository.save(expense);
    }

    public Expense get(Long id) {
        Optional<Expense> expense = expenseRepository.findById(id);
        return expense.orElseThrow(() -> new NotFoundException());
    }

    @Transactional
    public void updated(Long id, ExpenseDTO dto) {
        Expense expense = this.get(id);
        if (expense.getStatus() == 3) {
            throw new ForbiddenException(20006);
        }
        BeanUtils.copyProperties(dto, expense);
        expense.setStatus(1);
        expenseRepository.save(expense);
        //同步记录
        recordService.updateStatusToWait(2, expense.getId());
    }
}
